import { useState, useEffect } from 'react';
import Hole from './Hole';

type Difficulty = 'easy' | 'medium' | 'hard';

const DIFFICULTY_SETTINGS = {
  easy: { interval: 1000, duration: 30 },
  medium: { interval: 800, duration: 30 },
  hard: { interval: 600, duration: 30 }
};

const GameBoard = () => {
  // 使用单独的状态声明，避免复杂的状态对象
  const [score, setScore] = useState(0);
  const [highScore, setHighScore] = useState(0);
  const [timeLeft, setTimeLeft] = useState(30);
  const [isPlaying, setIsPlaying] = useState(false);
  const [activeHole, setActiveHole] = useState<number | null>(null);
  const [difficulty, setDifficulty] = useState<Difficulty>('medium');
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);

  const startGame = () => {
    setScore(0);
    setTimeLeft(DIFFICULTY_SETTINGS[difficulty].duration);
    setIsPlaying(true);
    setActiveHole(null);
  };

  const endGame = () => {
    setIsPlaying(false);
    setActiveHole(null);
    setShowConfirmDialog(false);
    if (score > highScore) {
      setHighScore(score);
    }
  };

  const whackMole = (index: number) => {
    if (!isPlaying) return;
    if (index === activeHole) {
      setScore(prev => prev + 1);
      setActiveHole(null);
    }
  };

  // 倒计时效果
  useEffect(() => {
    if (!isPlaying) return;
    
    if (timeLeft === 0) {
      endGame();
      return;
    }

    const timer = setInterval(() => {
      setTimeLeft(prev => prev - 1);
    }, 1000);

    return () => clearInterval(timer);
  }, [isPlaying, timeLeft]);

  // 地鼠出现效果
  useEffect(() => {
    if (!isPlaying) return;

    const showMole = () => {
      const randomHole = Math.floor(Math.random() * 9);
      setActiveHole(randomHole);
    };

    const gameInterval = setInterval(showMole, DIFFICULTY_SETTINGS[difficulty].interval);

    return () => clearInterval(gameInterval);
  }, [isPlaying, difficulty]);

  return (
    <div className="game-container">
      <div className="game-info">
        <div className="score">得分: {score}</div>
        <div className="high-score">最高分: {highScore}</div>
        <div className="timer">剩余时间: {timeLeft}秒</div>
      </div>

      <div className="difficulty-selector">
        {(['easy', 'medium', 'hard'] as const).map((diff) => (
          <button 
            key={diff}
            className={`difficulty-btn ${difficulty === diff ? 'active' : ''}`}
            onClick={() => setDifficulty(diff)}
            disabled={isPlaying}
          >
            {diff === 'easy' ? '简单' : diff === 'medium' ? '中等' : '困难'}
          </button>
        ))}
      </div>

      <div className="game-board">
        {Array(9).fill(null).map((_, index) => (
          <Hole
            key={index}
            isActive={index === activeHole}
            onClick={() => whackMole(index)}
          />
        ))}
      </div>

      <div className="button-group">
        {!isPlaying ? (
          <button 
            className="start-button" 
            onClick={startGame}
          >
            开始游戏
          </button>
        ) : (
          <button 
            className="end-button" 
            onClick={() => setShowConfirmDialog(true)}
          >
            结束游戏
          </button>
        )}
      </div>

      {timeLeft === 0 && (
        <div className="game-over">
          游戏结束！最终得分：{score}
          {score === highScore && score > 0 && ' (新纪录！)'}
        </div>
      )}

      {showConfirmDialog && (
        <div className="dialog-overlay">
          <div className="confirm-dialog">
            <h3>确定要结束游戏吗？</h3>
            <p>当前得分: {score}</p>
            <div className="dialog-buttons">
              <button 
                className="dialog-button confirm" 
                onClick={endGame}
              >
                确定
              </button>
              <button 
                className="dialog-button cancel" 
                onClick={() => setShowConfirmDialog(false)}
              >
                取消
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default GameBoard; 